package com.example.myapplication2003;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);

        EditText editText = findViewById(R.id.edit_text);
        // 监听输入框内容的变化
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 获取输入框内容，写入到sharedPreference;
                SharedPreferences sp = getSharedPreferences("todolist", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("text", s.toString());
                editor.commit();
                Log.i("tag", s.toString());   // 第一个参数表示 标签，第二个参数是log输出的内容
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 应用一打开，读取sharedPreference，如果有数据，显示到输入框（EditText组件）
        SharedPreferences sp = getSharedPreferences("todolist", Context.MODE_PRIVATE);
        String text = sp.getString("text", "");         // text就是保存的草稿
        editText.setText(text);

        // 定义模拟数据
        List<Map<String, Object>> data = new ArrayList<>();
        for(int i=0; i<0; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", i);
            map.put("item", "this is item " + i);
            data.add(map);
        }

        // 获取数据库SQLite管理对象
        SQLiteDatabase db = getApplicationContext().openOrCreateDatabase("testdb", Context.MODE_PRIVATE, null);
        String sql = "create table if not exists todolist(id int, text varchar(30))";
        db.execSQL(sql);

        // 读取数据库记录
        Cursor cursor = db.rawQuery("select * from todolist", null);
        while(cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String text2 = cursor.getString(1);
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("item", text2);
            data.add(map);
        }

        // 定义adapter
        String[] from = {"id", "item"};
        int[] to = {R.id.index, R.id.item};
        // 定义Adapter
        SimpleAdapter simpleAdapter =
                new SimpleAdapter(this,data,R.layout.list_view_item2,from,to);

        // 关联listview
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(simpleAdapter);   // 关联


        Button button = findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入框内容
                EditText editText = findViewById(R.id.edit_text);
                int id = data.size() + 1;
                String s = editText.getText().toString();
                Map<String, Object> map = new HashMap<>();
                map.put("id", id);
                map.put("item", s);
                // 要把数据添加到数组中
                data.add(map);
                // 数据更新以后，更新界面listview
                simpleAdapter.notifyDataSetChanged();

                // 清除sharedPreference中的数据
                SharedPreferences sp = getSharedPreferences("todolist", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.remove("text");              // 删除key为text的数据
                editor.commit();

                editText.setText("");               // 清空EditText组件内容

                // 要把输入的记录写入数据库
                String sql = "insert into todolist(id, text) values(?, ?)";
                db.execSQL(sql, new Object[]{id, s});
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 删除操作，1、删除数据库
                Map<String, Object> map = data.get(position);


                // 删除data数据（更新界面显示）

            }
        });

    }
}